from rest_framework import serializers
from .models import SystemLog


class SystemLogSerializer(serializers.ModelSerializer):
    """系统日志序列化器"""

    user_name = serializers.SerializerMethodField()
    user_role = serializers.SerializerMethodField()
    user_role_display = serializers.SerializerMethodField()
    created_at_display = serializers.SerializerMethodField()
    response_status_display = serializers.SerializerMethodField()

    class Meta:
        model = SystemLog
        fields = [
            'id', 'action', 'description', 'target_type', 'target_id',
            'ip_address', 'user_agent', 'request_data', 'response_status',
            'response_status_display', 'created_at', 'created_at_display',
            'user_name', 'user_role', 'user_role_display'
        ]

    def get_user_name(self, obj):
        """获取用户名称"""
        if obj.user:
            return f"{obj.user.real_name}({obj.user.username})"
        return "匿名用户"

    def get_user_role(self, obj):
        """获取用户角色"""
        if obj.user:
            return obj.user.role
        return None

    def get_user_role_display(self, obj):
        """获取用户角色显示名"""
        if obj.user:
            return obj.user.get_role_display()
        return "未知"

    def get_created_at_display(self, obj):
        """获取格式化的创建时间"""
        return obj.created_at.strftime('%Y-%m-%d %H:%M:%S')

    def get_response_status_display(self, obj):
        """获取响应状态显示"""
        if not obj.response_status:
            return "未知"

        status = obj.response_status
        if 200 <= status < 300:
            return f"{status} 成功"
        elif 300 <= status < 400:
            return f"{status} 重定向"
        elif 400 <= status < 500:
            return f"{status} 客户端错误"
        elif 500 <= status < 600:
            return f"{status} 服务器错误"
        else:
            return f"{status} 未知状态"


class SystemLogStatsSerializer(serializers.Serializer):
    """系统日志统计序列化器"""

    days = serializers.IntegerField(
        min_value=1,
        max_value=365,
        default=7,
        help_text="统计天数"
    )


class SystemLogBatchDeleteSerializer(serializers.Serializer):
    """批量删除日志序列化器"""

    DELETE_TYPE_CHOICES = [
        ('ids', '按ID删除'),
        ('date_range', '按时间范围删除'),
        ('all', '删除所有（保留最近N天）')
    ]

    type = serializers.ChoiceField(
        choices=DELETE_TYPE_CHOICES,
        help_text="删除类型"
    )

    ids = serializers.ListField(
        child=serializers.IntegerField(),
        required=False,
        help_text="要删除的日志ID列表"
    )

    start_date = serializers.DateField(
        required=False,
        help_text="开始日期"
    )

    end_date = serializers.DateField(
        required=False,
        help_text="结束日期"
    )

    keep_days = serializers.IntegerField(
        min_value=1,
        max_value=365,
        default=7,
        required=False,
        help_text="保留最近N天的日志"
    )

    def validate(self, attrs):
        """验证删除参数"""
        delete_type = attrs.get('type')

        if delete_type == 'ids':
            if not attrs.get('ids'):
                raise serializers.ValidationError('按ID删除时必须提供ID列表')

        elif delete_type == 'date_range':
            if not attrs.get('start_date'):
                raise serializers.ValidationError('按时间范围删除时必须提供开始日期')

        return attrs


class SystemLogExportSerializer(serializers.Serializer):
    """日志导出序列化器"""

    FORMAT_CHOICES = [
        # ('csv', 'CSV格式'),
        ('json', 'JSON格式')
    ]

    format = serializers.ChoiceField(
        choices=FORMAT_CHOICES,
        default='csv',
        help_text="导出格式"
    )

    start_date = serializers.DateField(
        required=False,
        help_text="开始日期"
    )

    end_date = serializers.DateField(
        required=False,
        help_text="结束日期"
    )

    filters = serializers.DictField(
        required=False,
        help_text="筛选条件"
    )

    def validate_filters(self, value):
        """验证筛选条件"""
        if not value:
            return {}

        # 验证支持的筛选字段
        allowed_fields = ['action', 'target_type', 'user', 'ip_address', 'response_status']
        filtered_data = {}

        for field, field_value in value.items():
            if field in allowed_fields and field_value:
                filtered_data[field] = field_value

        return filtered_data


class SystemLogFilterSerializer(serializers.Serializer):
    """日志筛选序列化器"""

    page = serializers.IntegerField(min_value=1, default=1)
    page_size = serializers.IntegerField(min_value=1, max_value=100, default=20)

    # 筛选字段
    action = serializers.CharField(required=False, max_length=100)
    target_type = serializers.CharField(required=False, max_length=50)
    user = serializers.CharField(required=False, max_length=100)
    start_date = serializers.DateField(required=False)
    end_date = serializers.DateField(required=False)
    ip_address = serializers.CharField(required=False, max_length=50)
    response_status = serializers.IntegerField(required=False, min_value=100, max_value=599)
    search = serializers.CharField(required=False, max_length=200)

    def validate(self, attrs):
        """验证筛选参数"""
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')

        # 验证日期范围
        if start_date and end_date and start_date > end_date:
            raise serializers.ValidationError('开始日期不能晚于结束日期')

        return attrs